<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;


class ActivityDiamondCost extends  Model{

	protected $table='game_activity_diamond_cost';
    protected $_db_select = 'mysql';
    public function selectdb(){
        if ($select) {
            return $this->_db_select = $select;
        }
        return $this->_db_select;
    }
    public function getConnectionName(){
        return $this->selectdb();
    }
    public static function with($relations)
    {
        return new static;
    }
    public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);
        // $reward_date = Request::get('reward_date', 0);
        
        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table($this->table)->orderBy("diamond_cost", "desc");
        self::SourceCondition($rw);
        
        $total = $rw->get()->count();
        $rw->skip($start)->take($perPage);
        $data = $rw->get()->toArray();

        $send_obj = new self();
        $send_obj->area = Request::get('area');
        // $send_obj->act_type =  $act_type;
        // $active_acts = self::syncToGame($send_obj, Request::get('area'), 'get_ids') ?: [];

        // foreach ($data as &$obj) {

        //     $obj->act_object = empty($obj->act_object) ? [] : json_decode($obj->act_object, true);
        //     $obj->item_list = empty($obj->item_list) ? [] : json_decode($obj->item_list, true);
        //     $obj->active = in_array($obj->act_id, $active_acts) ? 1: 0;
        // }

        

        // $data = json_decode($data, true);
        // \Log::debug(__METHOD__, [$rw->toSql()]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }    

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
      
        if ($cond['reward_date']){
            $rw->where('created_at', self::getRewardInt($cond['reward_date']));
        }
        if ($cond["area"] or $cond['area']){
            $rw->where("area", $cond['area'] ?: $cond['area']);
        }

    }
    // 创建返利数据
    public static function generateReward() {
        $reward_date = Request::get('reward_date', strtotime('-1 day'));

        \Log::info('[DIAMOND_REBATE_GENERATE]DATE['.$reward_date.']');
        $list = \App\Models\Area::areaSelectData();
        
        foreach ($list as $area => $name) {
            self::rewardByArea($area, $reward_date);
        }
    }
    public static function rewardByArea($area, $reward_date = null) {
        self::CloseRemoteConn();
        \App\Models\Area::RemoteBgsiSelectByArea($area);
        $start = self::getRewardInt($reward_date);
        $end = $start + 86400;
        $rw = \DB::connection('remote_bgsi')->table('behavior_log')->select('player_id', \DB::Raw('sum(op_val_1) as total_cost'), \DB::Raw('max(level) as level') )
        ->where('created_at', '>=', $start)->where('created_at', '<=', $end)->where('op', 'S.DIAMOND_REDUCE')
        ->groupBy('player_id');
        $total = $rw->get()->count();
        $list = $rw->get()->toArray();

        \Log::info('[DIAMOND_REBATE_GENERATE]AREA['.$area.']TOTAL['.$total.']', [$start, $end]);
        foreach ($list as $obj) {
            $param = [
                'area' => $area,
                'player_id' => $obj->player_id,
                'level' => $obj->level,
                'diamond_cost' => $obj->total_cost,
            ];
            self::rewardOnePlayer($obj->player_id, $param, $reward_date);
        }
        
    }

    // 返回单个玩家 奖励邮件
    /**
     * @player_id           int         角色id
     * @cost_data           array       拥有的钻石数
     * @reward_date         int         返利日期
     */
    public static function rewardOnePlayer($player_id, $cost_data, $reward_date = null) {
        $table_name = 'game_activity_diamond_cost';
        $reward_int = self::getRewardInt($reward_date);

        if ( empty($player_id)) {
            
            return;
        }
        
        $one = \DB::table($table_name)->where('player_id', $player_id)->where('created_at', $reward_int)->where('deleted_at', 0)->first();

        if ($one ) {
            \Log::info("[DIAMOND_COST_REBATE]PID[".$player_id."]HAD send email reward!!" . "");
            return;
        }
        $data['player_id'] = $player_id;
        $data['level'] = $cost_data['level'];
        $data['area'] = $cost_data['area'];
        $data['diamond_cost'] = $cost_data['diamond_cost'];
        $data['created_at'] = self::getRewardInt($reward_date);
        $data['diamond_reward'] = self::genRewardDiamond($cost_data['level'], $cost_data['diamond_cost']);

        \Log::debug('----------- -----------------   ---------------',[$data]);
        if (empty($data['diamond_reward'])) {
            return;
        }
        \DB::table($table_name)->insert($data);
    }

    public static function getRewardInt($reward_date = 0) {
        if ((string)(intval($reward_date)) !== (string)($reward_date)) {
            $reward_date = strtotime($reward_date);
        }

        // if (empty($reward_date)) {
        $reward_date = strtotime(date("Y-m-d", $reward_date ?:time()));
        // } 
            
        return $reward_date;
    }

    // 获取返利的钻石
    public static function genRewardDiamond($level, $diamond) {
        if (empty ($diamond)) {
            return 0;
        }
        $rule = self::genRewardDiamondRule($level);

        $reward_diamond = $rule['rate'] * $diamond;

        return $reward_diamond;
    }

    // 获取返利的对象
    public static function genRewardDiamondRule($level) {

        $rule = self::getRewardRule();

       
        $use_key = 0;
        foreach ($rule as $k => $r) {
            if ($k == 0 && $r['level'] > $level) {
                return 0;
            }

            if ($level >= $r['level']) {
                $use_key = $k;
            }

        }

        return $rule[$use_key];
    }


    // 关闭远程数据库连接
    public static function CloseRemoteConn()
    {
        if ( ! \Config::get("database.connections.remote_bgsi") ) {
            return;
        }
        
        \DB::disconnect('remote_bgsi');
    }

    // 发送邮件到game
    public static function sendToGame() {
        $table = 'game_activity_diamond_cost';
        $rw = \DB::table($table)->orderBy("id", "desc");
        self::SourceCondition($rw);
        $data = $rw->get()->toArray();


        foreach ( $data as $obj) {
            if ($obj->send_ts >= 1) {
            break;
            }
            $one = self::conv2mail($obj);
            \App\Models\EMail::sendByPlayerId($one, $obj->player_id, $obj->area);
            
            $times = intval($obj->send_ts) + 1;
            \DB::table($table)->where('id', $obj->id)->update(['send_ts'=> $times]);
        }

        
    }

    public static function conv2mail($obj) {
        $rule = self::genRewardDiamondRule($obj->level);
        $one = new \stdClass;
        $one->title = $rule['title'];
        $one->content = $rule['content'];
        $one->prop = [['id'=> 114000200, 'at' => $obj->diamond_reward]];
        $one->receiver == $obj->player_id;
        $one->receive_method = 1;
        return $one;
    }

    public static function getRewardRule() {
        return [
            ['level'=> 15,'rate' => 0.2,  'title' => '15级返利钻石', 'content' => '您在昨日冲级活动中达到了15级，特此返还总消费20%钻石，感谢您的支持与鼓励！\n\n官方QQ群：839439409，加群更有惊喜大礼相送~'],
            ['level'=> 20,'rate' => 0.4,  'title' => '20级返利钻石', 'content' => '您在昨日冲级活动中达到了20级，特此返还总消费40%钻石，感谢您的支持与鼓励！\n\n官方QQ群：839439409，加群更有惊喜大礼相送~'],
            ['level'=> 30,'rete' => 0.8,  'title' => '30级返利钻石', 'content' => '您在昨日冲级活动中达到了30级，特此返还总消费80%钻石，感谢您的支持与鼓励！\n\n官方QQ群：839439409，加群更有惊喜大礼相送~'],
        ];
    }
}